﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace monitor_client
{
    public delegate void sort_delegate(int a);
    public delegate void oblDelegat(string a);
    public delegate void ControlDelegate(Control a);
    public delegate void FormCloseDelegate(Form a);

    public partial class JournalForm : Form
    {
        class ListViewItemComparer : IComparer
        {
            private int col;
            public ListViewItemComparer(int column)
            {
                /*if (column == 0)
                    col = 5;
                else*/
                    col = column;

            }
            public int Compare(object x, object y)
            {
                int ret = 0;
                DateTime dt1, dt2;
                string d1str = ((ListViewItem)x).SubItems[col].Text;
                string d2str = ((ListViewItem)y).SubItems[col].Text;
                //--------------------------Сортировка по столбцам, содержащим дату
                /*if (DateTime.TryParseExact(((ListViewItem)x).SubItems[col].Text, "dd.MM/HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt1))
                {
                    if (((ListViewItem)y).SubItems[col].Text == "Нет данных")
                    {
                        if (!comp)
                            dt2 = DateTime.ParseExact("01.01/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                        else
                            dt2 = DateTime.ParseExact("31.12/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    }
                    else
                        dt2 = DateTime.ParseExact(((ListViewItem)y).SubItems[col].Text, "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    ret = DateTime.Compare(dt1, dt2);
                }
                else if (((ListViewItem)x).SubItems[col].Text == "Нет данных")
                {
                    if (!comp)
                        dt1 = DateTime.ParseExact("01.01/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    else
                        dt1 = DateTime.ParseExact("31.12/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    if (((ListViewItem)y).SubItems[col].Text == "Нет данных")
                        dt2 = DateTime.ParseExact("01.01/00:00", "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    else
                        dt2 = DateTime.ParseExact(((ListViewItem)y).SubItems[col].Text, "dd.MM/HH:mm", CultureInfo.InvariantCulture);
                    ret = DateTime.Compare(dt1, dt2);
                }
                //--------------------------
                else
                    ret = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
                if (!comp)
                    ret *= -1;
                return ret;*/
                if (DateTime.TryParse(d1str, out dt1))
                {
                    if (DateTime.TryParse(d2str, out dt2))
                        ret = DateTime.Compare(dt1, dt2);
                    else
                        ret = -1;
                }
                else if (d1str == "Нет данных")
                {
                    ret = String.Compare(d1str, d2str);
                }
                else
                    ret = String.Compare(d1str, d2str);
                if (!comp)
                    ret *= -1;
                return ret;
            }
        }

        //int port = 38802;                   //порт для запроса логов
        //int lport;                          //38000;
        //Socket soc;
        //IPEndPoint lpe, ipe;
        byte[] send = new byte[12];
        static bool comp = true;
        fclose d;
        //DateTime dt1, dt2;
        int preColumn = 0;
        string[] obls;
        int access_type = 0;
        
        //public Form6(fclose sender1, DateTime sender2, DateTime sender3, form5_m sender4)
        //public Form6(fclose sender1, string[] sender2)
        public JournalForm(fclose sender1, rec_options sender2)
        {
            //sender3 = ThisFormClose();
            InitializeComponent();
            d = sender1;
            obls = (string[])sender2.oblast.Clone();
            access_type = sender2.access;
            /*
            fm = sender4;
            dt1 = sender2;
            dt2 = sender3;
             */
            listView1.View = View.Details;
            listView1.FullRowSelect = true;
            toolStripStatusLabel1.Text = "Подключение к БД...";
            /*send[0] = (byte)'l';
            send[1] = (byte)'o';
            send[2] = (byte)'g';
            send[3] = (byte)'r';
            send[4] = (byte)'e';
            send[5] = (byte)'q';*/
        }

        private void sort_lv(int a)
        {
            listView1.ListViewItemSorter = new ListViewItemComparer(a);
            for (int i = 0; i < listView1.Items.Count; i++)
                listView1.Items[i].Text = string.Concat(listView1.Items[i].Index + 1);
        }

        private void ThisFormClose()
        {
            d(false);
            //fm(false, true);            
            this.Close();
        }

        private void menu3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*d(false);
            //fm(false, true);            
            this.Close();*/
            ThisFormClose();
        }

        private void menu2ToolStripMenuItem_Click(object sender, EventArgs e)
        {            
        }

        private void ControlEnableInvoke(Control control)
        {
                control.Enabled = true;
        }

        private void ControlDisableInvoke(Control control)
        {
                control.Enabled = false;
        }

        private void FormCloseInvoke(Form form)
        {
            form.Close();
        }

        private void DBconnect()
        {
            while (true)
            {
                toolStripStatusLabel1.Text = "Подключение к БД...";
                if (DBOperations.DBConnect())
                {
                    toolStripStatusLabel1.Text = "Готово.";
                    ControlDelegate cd = ControlEnableInvoke;
                    comboBox1.Invoke(cd, comboBox1);
                    //comboBox1.Enabled = true;
                    Thread.CurrentThread.Abort();
                    return;
                }
                else
                {                    
                    toolStripStatusLabel1.Text = "Нет связи с БД.";
                    ControlDelegate cd = ControlDisableInvoke;
                    comboBox1.Invoke(cd, comboBox1);
                    DialogResult res = new DialogResult();
                    res = MessageBox.Show("Не удалось установить соединение с БД. Повторить?", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question);
                    if (res == DialogResult.Cancel)
                    {
                        d(false);
                        FormCloseDelegate fcd = FormCloseInvoke;
                        this.Invoke(fcd, this);
                        Thread.CurrentThread.Abort();
                        return;
                    }
                }
            }
        }

        private void Form6_Load(object sender, EventArgs e)
        {
            menu1ToolStripMenuItem.Enabled = false;
            label5.BringToFront();        
            comboBox1.Enabled = false;            
            button1.Enabled = false;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            string[] cb1 = new string[] { "Анализаторы", "Измерители" };
            comboBox1.Items.AddRange(cb1);
            string[] cb23 = new string[] { "Брестская", "Витебская", "Гомельская", "Гродненская", "Минская", "Могилевская", "Вся Беларусь" };
            comboBox2.Items.AddRange(cb23);
            comboBox3.DropDownStyle = ComboBoxStyle.DropDown;
            comboBox3.AutoCompleteMode = AutoCompleteMode.Append;
            comboBox3.Items.AddRange(cb23);
            comboBox4.DropDownStyle = ComboBoxStyle.DropDownList;
            string[] cb4 = new string[] { "Alarm", "Warning", "Info", "System", "Все" };
            comboBox4.Items.AddRange(cb4);
            comboBox5.DropDownStyle = ComboBoxStyle.DropDownList;
            string[] cb5 = new string[] { "RF", "ASI", "RF & ASI" };
            comboBox5.Items.AddRange(cb5);
            string[] cb6 = new string[26];
            for (int i = 0; i < 26; i++)
                cb6[i] = "BLR" + (i + 1).ToString();
            comboBox6.Items.AddRange(cb6);
            groupBox1.Visible = false;
            groupBox2.Visible = false;
            groupBox3.Visible = false;

            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "dd MMMM yyyy - HH:mm";
            dateTimePicker1.MinDate = DateTime.Parse("6.12.2012");
            //dateTimePicker1.MaxDate = DateTime.Now;
            dateTimePicker2.Format = DateTimePickerFormat.Custom;
            dateTimePicker2.CustomFormat = "dd MMMM yyyy - HH:mm";
            dateTimePicker2.MinDate = DateTime.Parse("7.12.2012");
            //dateTimePicker2.MaxDate = DateTime.Now;
            if (obls.Length == 1 && access_type != 1)
            {
                string obl = "";
                switch (obls[0])
                {
                    case "brest":
                        obl = "Брестская";
                        break;
                    case "viteb":
                        obl = "Витебская";
                        break;
                    case "gomel":
                        obl = "Гомельская";
                        break;
                    case "grodn":
                        obl = "Гродненская";
                        break;
                    case "minsk":
                        obl = "Минская";
                        break;
                    case "mogil":
                        obl = "Могилевская";
                        break;
                }
                comboBox2.Text = obl;
                comboBox2.Enabled = false;
                button2.Visible = false;
                comboBox3.Text = obl;
                comboBox3.Enabled = false;
                button4.Visible = false;
            }
            /*
            byte[] buf = new byte[4];
            byte[] buf_d, buf_d_write;
            string name;
            int kol, i, len, count = 1;
            lport = 38000;
            send[6] = (byte)dt1.Month;
            send[7] = (byte)(dt1.Year / 100);
            send[8] = (byte)(dt1.Year % 100);
            send[9] = (byte)dt2.Month;
            send[10] = (byte)(dt2.Year / 100);
            send[11] = (byte)(dt2.Year % 100);
            soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soc.SendTimeout = 5;
            soc.ReceiveTimeout = 5;
            lpe = new IPEndPoint(IPAddress.Any, lport);
            bool ec = true;
            while (ec)
            {
                try
                {
                    soc.Bind(lpe);
                    ec = false;
                }
                catch (SocketException)
                {
                    lport--;
                    lpe = new IPEndPoint(IPAddress.Any, lport);
                }
            }
            string ips = File.ReadAllText(@"resources\server");
            IPAddress ip = IPAddress.Parse(ips);
            ipe = new IPEndPoint(ip, port);
            try
            {
                if (!soc.Connected)
                    soc.Connect(ipe);
            }
            catch (Exception)
            {
                soc.Close();                
                return;
            }
            soc.Send(send);             //----------запрос логов---------- logreq[m1][y1:1/2][y1:2/2][m2][y2:1/2][y2:2/2]            
            soc.Receive(buf);
            kol = BitConverter.ToInt32(buf, 0);
            string[] gf;
            if (!Directory.Exists(@"resources\temp_logs"))
                Directory.CreateDirectory(@"resources\temp_logs");
            else
            {
                gf = Directory.GetFiles(@"resources\temp_logs");
                for (i = 0; i < gf.Length; i++)
                {
                    File.Delete(gf[i]);
                }
            }
            StreamWriter sw;
            for (i = 0; i < kol; i++)
            {
                soc.Receive(buf);
                len = BitConverter.ToInt32(buf, 0);
                buf_d = new byte[len];
                soc.Receive(buf_d);
                buf_d_write = new byte[buf_d.Length - 14];
                Array.Copy(buf_d, 14, buf_d_write, 0, buf_d.Length - 14);
                name = Encoding.Default.GetString(buf_d, 0, 14);
                sw = new StreamWriter(@"resources\temp_logs\" + name + ".csv", false, Encoding.GetEncoding("Windows-1251"));
                sw.Write(Encoding.GetEncoding("Windows-1251").GetString(buf_d_write));
                sw.Close();
            }

            //-----Открываем файлы журнала--------------
            gf = Directory.GetFiles(@"resources\temp_logs");
            string[] str;
            int j = 0;
            for (j = 0; j < gf.Length; j++)
            {
                try
                {
                    str = File.ReadAllLines(gf[j], Encoding.GetEncoding("Windows-1251"));
                }
                catch (Exception)
                {
                    System.Windows.Forms.MessageBox.Show("Файл используется другим процессом", "Ошибка открытия файла");
                    d(false);
                    return;
                }
                ListViewItem[] item;
                toolStripStatusLabel1.Text = "lol";
                item = new ListViewItem[str.Length - 1];
                int ss1, ss2;
                count = 0;
                for (i = 0; i < str.Length - 1; i++)   //-----Создание элементов списка
                {
                    ss1 = ss2 = 0;
                    item[i] = new ListViewItem(String.Concat(count));
                    while (str[i + 1].Substring(ss1, 1) != ";")
                        ss1++;
                    item[i].SubItems.Add(str[i + 1].Substring(0, ss1));
                    ss2 = ss1 + 1;
                    while (str[i + 1].Substring(ss2, 1) != ";")
                        ss2++;
                    item[i].SubItems.Add(str[i + 1].Substring(ss1 + 1, ss2 - ss1 - 1));
                    ss1 = ss2 + 1;
                    while (str[i + 1].Substring(ss1, 1) != ";")
                        ss1++;
                    item[i].SubItems.Add(str[i + 1].Substring(ss2 + 1, ss1 - ss2 - 1));
                    ss2 = ss1 + 1;
                    while (str[i + 1].Substring(ss2, 1) != ";")
                        ss2++;
                    item[i].SubItems.Add(str[i + 1].Substring(ss1 + 1, ss2 - ss1 - 1));
                    ss1 = ss2 + 1;
                    while (str[i + 1].Substring(ss1, 1) != ";")
                        ss1++;
                    item[i].SubItems.Add(str[i + 1].Substring(ss2 + 1, ss1 - ss2 - 1));
                    ss2 = ss1 + 1;
                    while (str[i + 1].Substring(ss2, 1) != ";")
                        ss2++;
                    item[i].SubItems.Add(str[i + 1].Substring(ss1 + 1, ss2 - ss1 - 1));
                    if (string.Compare(str[i + 1].Substring(ss2 + 1), "0") != 0)
                        item[i].SubItems.Add(str[i + 1].Substring(ss2 + 1));
                    else item[i].SubItems.Add("Нет данных");
                    listView1.Items.Add(item[i]);
                    count++;
                }
            }
            soc.Shutdown(SocketShutdown.Both);
            soc.Close();  
            */    
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == 0)
                return;
            if (!(preColumn != e.Column && !((e.Column == 0 || e.Column == 5) && (preColumn == 0 || preColumn == 5))))
                comp = !comp;
            preColumn = e.Column;
            sort_delegate sort = sort_lv;
            listView1.Invoke(sort, e.Column);
            
        }

        private void Form6_FormClosing(object sender, FormClosingEventArgs e)
        {
            d(false);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            menu1ToolStripMenuItem.Enabled = true;
            label5.Visible = false;
            string type = (string)((ComboBox)sender).SelectedItem;
            if (!groupBox3.Visible)
                groupBox3.Visible = true;
            setupTable();
            switch (type)
            {
                case "Измерители":
                    groupBox2.Visible = false;
                    groupBox1.Visible = true;
                    groupBox1.BringToFront();
                    break;
                case "Анализаторы":
                    groupBox1.Visible = false;
                    groupBox2.Visible = true;
                    groupBox2.BringToFront();
                    break;
            }
            button1.Enabled = true;
        }

        private void setupTable()
        {
            listView1.Clear();
            switch((string)comboBox1.SelectedItem)
            {
                case "Измерители":
                    listView1.Columns.Add("№");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 40;
                    listView1.Columns.Add("Область");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 90;
                    listView1.Columns.Add("Зона выделеня");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 96;
                    listView1.Columns.Add("Наименование РТПС");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 150;
                    listView1.Columns.Add("Тип аварии");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 75;
                    listView1.Columns.Add("Дата аварии");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 120;
                    listView1.Columns.Add("Дата исправления");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 130;
                    break;
                case "Анализаторы":
                    listView1.Columns.Add("№");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 40;
                    listView1.Columns.Add("Область");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 90;
                    listView1.Columns.Add("Наименование РТПС");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 150;
                    listView1.Columns.Add("Вход/Выход");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 80;
                    listView1.Columns.Add("Состояние");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 80;
                    listView1.Columns.Add("Дата");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 130;
                    listView1.Columns.Add("Класс");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 70;
                    listView1.Columns.Add("Событие");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 200;
                    listView1.Columns.Add("Детали");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 70;
                    listView1.Columns.Add("PID");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 60;
                    listView1.Columns.Add("Сервис");
                    listView1.Columns[listView1.Columns.Count - 1].Width = 80;

                    break;
            }
        
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AddRegionForm form5 = new AddRegionForm(new oblDelegat(AddObl2));
            form5.ShowDialog();
        }

        private void AddObl2(string str)
        {
            if (comboBox2.Text.Trim() == "Область")
                comboBox2.Text = str;
            else
                comboBox2.Text += ", " + str;
        }

        private void AddObl3(string str)
        {
            if (comboBox3.Text.Trim() == "Область")
                comboBox3.Text = str;
            else
                comboBox3.Text += ", " + str;
        }

        private ListViewItem[] SelectAnalizators(string d1, string d2)
        {
            string st = comboBox3.Text;
            string tbRTPS = textBox5.Text;
            string cbVhVih = comboBox5.Text;
            string cbClass = comboBox4.Text;
            string tbEvent = textBox4.Text;
            ListViewItem[] items = new ListViewItem[1];
            int lvi_count = 1;
            if (st == "Область" || st.Contains("Вся Беларусь"))
                st = "";
            if (tbRTPS == "РТПС")
                tbRTPS = "";
            if (comboBox5.SelectedIndex == -1)
                cbVhVih = "";
            if (comboBox4.SelectedIndex == -1 || cbClass == "Все")
                cbClass = "";
            if (tbEvent == "Событие")
                tbEvent = "";
            if (cbVhVih == "RF & ASI")
                cbVhVih = "";
            string select = st + ";"
                          + tbRTPS + ";"
                          + cbVhVih + ";"
                          + d1 + ","
                          + d2 + ";"
                          + cbClass + ";"
                          + tbEvent;
            //DBOperations.DBConnect();
            string[] SelStr = DBOperations.SelectAnalyze(select);
            items = new ListViewItem[SelStr.Length];
            foreach (string str in SelStr)
            {
                ListViewItem lvi = new ListViewItem(lvi_count.ToString());
                for (int i = 0; i < str.Split(';').Length; i++)
                    lvi.SubItems.Add(str.Split(';')[i]);
                //listView1.Items.Add(lvi);
                items[lvi_count - 1] = lvi;
                lvi_count++;
            }
            if (lvi_count == 1)
                toolStripStatusLabel1.Text = "Совпадений не найдено.";
            else
                toolStripStatusLabel1.Text = "Найдено " + (lvi_count - 1).ToString() + " совпадений.";
            return items;
        }

        private ListViewItem[] SelectIzmers(string d1, string d2)
        {
            string st = comboBox2.Text;
            string cbBLR = comboBox6.Text;
            string tbRTPS = textBox2.Text;
            string tbErr = textBox3.Text;
            ListViewItem[] items = new ListViewItem[1];
            int lvi_count = 1;
            if (st == "Область" || st.Contains("Вся Беларусь"))
                st = "";
            if (cbBLR == "BLR")
                cbBLR = "";
            if (tbRTPS == "РТПС")
                tbRTPS = "";
            if (tbErr == "Тип аварии")
                tbErr = "";
            string select = st + ";"
                          + cbBLR + ";"
                          + tbRTPS + ";"
                          + tbErr + ";"
                          + d1 + ","
                          + d2;
            //DBOperations.DBConnect();
            string[] SelStr = DBOperations.SelectIzmers(select);
            items = new ListViewItem[SelStr.Length];
            foreach (string str in SelStr)
            {
                if (str.Contains("26:59"))
                {
                    items[lvi_count - 1].Remove();
                    continue;
                }
                ListViewItem lvi = new ListViewItem(lvi_count.ToString());
                for (int i = 0; i < str.Split(';').Length; i++)
                {
                    DateTime date;
                    if (DateTime.TryParse(str.Split(';')[i], out date))
                        lvi.SubItems.Add(date.ToString("dd.MM.yyyy HH:mm"));
                    else
                        lvi.SubItems.Add(str.Split(';')[i]);
                }
                //listView1.Items.Add(lvi);
                items[lvi_count - 1] = lvi;
                lvi_count++;
            }
            if (lvi_count == 1)
                toolStripStatusLabel1.Text = "Совпадений не найдено.";
            else
                toolStripStatusLabel1.Text = "Найдено " + (lvi_count - 1).ToString() + " совпадений.";
            return items;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            //int lvi_ColCount = listView1.Columns.Count;
            //ListView.ColumnHeaderCollection colH = listView1.Columns;
            ListViewItem[] items = new ListViewItem[1];
            ColumnHeader[] colH = new ColumnHeader[listView1.Columns.Count];
            int ij = 0;
            foreach (ColumnHeader col in listView1.Columns)
            {
                colH[ij] = col;
                ij++;
            }
            listView1.Clear();
            listView1.Columns.AddRange(colH);
            toolStripStatusLabel1.Text = "Обработка запроса...";
            if (!DBOperations.ISConnected)
                DBOperations.DBConnect();
            /*int j = listView1.Items.Count;
            for (int i = 0; i < j; i++)
            {
                //Удаляем каждый нулевой элемент столько раз, сколько было элементов до начала удаления.
                //При удалении элемента, все порядковые номера (индексы) элементов смещаются на 1 к младшему.
                listView1.Items.RemoveAt(0);
            }*/
            string date1, date2;
            date1 =     dateTimePicker1.Value.ToShortDateString() + " "
                        + dateTimePicker1.Value.Hour.ToString() + ":"
                        + dateTimePicker1.Value.Minute.ToString() + ":00";

            date2 =     dateTimePicker2.Value.ToShortDateString() + " "
                        + dateTimePicker2.Value.Hour.ToString() + ":"
                        + dateTimePicker2.Value.Minute.ToString() + ":59";
            
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    items = SelectAnalizators(date1, date2);
                    break;
                case 1:
                    items = SelectIzmers(date1, date2);
                    break;
            }
            if (DBOperations.ISConnected)
                DBOperations.CloseConnect();
            listView1.BeginUpdate();
            listView1.Items.AddRange(items);
            for (int i = 0; i < listView1.Items.Count; i++)
                listView1.Items[i].Text = string.Concat(listView1.Items[i].Index + 1);
            listView1.EndUpdate();
            button1.Enabled = true;
        }

        private void Form6_Shown(object sender, EventArgs e)
        {
            ThreadStart ts = DBconnect;
            Thread thread = new Thread(ts);
            thread.Start();
            //DBconnect();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            AddRegionForm form5 = new AddRegionForm(new oblDelegat(AddObl3));
            form5.ShowDialog();
        }

        private void textBox5_Enter(object sender, EventArgs e)
        {
            if (textBox5.Text.Trim() == "РТПС")
                textBox5.Text = "";
        }

        private void textBox4_Enter(object sender, EventArgs e)
        {
            if (textBox4.Text.Trim() == "Событие")
                textBox4.Text = "";
        }

        private void comboBox3_Enter(object sender, EventArgs e)
        {
            if (comboBox3.Text.Trim() == "Область")
                comboBox3.Text = "";
        }

        private void textBox3_Enter(object sender, EventArgs e)
        {
            if (textBox3.Text.Trim() == "Тип аварии")
                textBox3.Text = "";
        }

        private void textBox2_Enter(object sender, EventArgs e)
        {
            if (textBox2.Text.Trim() == "РТПС")
                textBox2.Text = "";
        }

        private void comboBox2_Enter(object sender, EventArgs e)
        {
            if (comboBox2.Text.Trim() == "Область")
                comboBox2.Text = "";
        }

        private void comboBox2_Leave(object sender, EventArgs e)
        {
            if (comboBox2.Text.Trim() == "")
                comboBox2.Text = "Область";
        }

        private void textBox2_Leave(object sender, EventArgs e)
        {
            if (textBox2.Text.Trim() == "")
                textBox2.Text = "РТПС";
        }

        private void textBox3_Leave(object sender, EventArgs e)
        {
            if (textBox3.Text.Trim() == "")
                textBox3.Text = "Тип аварии";
        }

        private void comboBox3_Leave(object sender, EventArgs e)
        {
            if (comboBox3.Text.Trim() == "")
                comboBox3.Text = "Область";
        }

        private void textBox5_Leave(object sender, EventArgs e)
        {
            if (textBox5.Text.Trim() == "")
                textBox5.Text = "РТПС";
        }

        private void textBox4_Leave(object sender, EventArgs e)
        {
            if (textBox4.Text.Trim() == "")
                textBox4.Text = "Событие";
        }

        private void comboBox6_Enter(object sender, EventArgs e)
        {
            if (comboBox6.Text.Trim() == "BLR")
                comboBox6.Text = "";
        }

        private void comboBox6_Leave(object sender, EventArgs e)
        {
            if (comboBox6.Text.Trim() == "")
                comboBox6.Text = "BLR";
        }


        private string[] GetItems()
        {
            string[] str = new string[listView1.Items.Count];
            int i = 0;
            foreach (ListViewItem lvi in listView1.Items)
            {
                int j = 0;
                foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems)
                {
                    if (j == lvi.SubItems.Count - 1)
                        str[i] += lvsi.Text + "\r\n";
                    else
                        str[i] += lvsi.Text + ";";
                    j++;
                }
                i++;
            }
            return str;
        }

        private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string[] str = GetItems();
            Stream myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.InitialDirectory = @"C:\";
            saveFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.DefaultExt = ".csv";
            saveFileDialog1.AddExtension = true;

            


            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream fs;
                try
                {
                    fs = File.OpenWrite(saveFileDialog1.FileName);
                }
                catch (Exception)
                {
                    MessageBox.Show("Невозможно выполнить запись в выбранный файл.");
                    return;
                }
                fs.Close();
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    ColumnHeader[] colH = new ColumnHeader[listView1.Columns.Count];
                    foreach (ColumnHeader col in listView1.Columns)
                    {
                        myStream.Write(Encoding.Default.GetBytes(col.Text), 0, col.Text.Length);
                        myStream.WriteByte((byte)';');
                    }
                    byte[] b = new byte[2];
                    b[0] = (byte)'\r';
                    b[1] = (byte)'\n';
                    myStream.Write(b, 0, b.Length);
                    myStream.Write(b, 0, b.Length);
                    // Code to write the stream goes here.
                    foreach (string st in str)
                    {
                        myStream.Write(Encoding.Default.GetBytes(st), 0, st.Length);
                    }
                    myStream.Close();
                    MessageBox.Show("Сохранение успешно завершено.");
                }
            }
        }

        private void toolStripStatusLabel1_TextChanged(object sender, EventArgs e)
        {
        }

        

    }
}
